#include "Field.h"

void Field::SetColumType(const std::string& columnType)
{
	//m_ColumnType = columnType;

	// ͳһΪСд
	std::string colType = columnType;
	for (auto& ch : colType) ch = static_cast<char>(tolower(ch));

	auto extract1 = [](const std::string& s) -> int {
		size_t l = s.find('(');
		size_t r = s.find(')');
		if (l != std::string::npos && r != std::string::npos && r > l + 1) {
			return std::stoi(s.substr(l + 1, r - l - 1));
		}
		return 0;
	};

	auto extract2 = [](const std::string& s, int& m, int& d) {
		size_t l = s.find('(');
		size_t r = s.find(')');
		if (l != std::string::npos && r != std::string::npos && r > l + 1) {
			std::string inner = s.substr(l + 1, r - l - 1);
			size_t comma = inner.find(',');
			if (comma != std::string::npos) {
				m = std::stoi(inner.substr(0, comma));
				d = std::stoi(inner.substr(comma + 1));
			}
		}
	};

	if (colType._Starts_with("bigint")) SetType(Type::BigInt);
	else if (colType._Starts_with("binary")) {
		SetType(Type::Binary);
		m_DataLen = extract1(colType);
	}
	else if (colType._Starts_with("blob")) SetType(Type::Blob);
	else if (colType._Starts_with("tinyint(1)")) SetType(Type::Boolean);  // MySQL boolean
	else if (colType._Starts_with("char")) {
		SetType(Type::Char);
		m_DataLen = extract1(colType);
	}
	else if (colType._Starts_with("decimal")) {
		SetType(Type::Decimal);
		extract2(colType, m_Decimal_M, m_Decimal_D);
	}
	else if (colType._Starts_with("date")) SetType(Type::Date);
	else if (colType._Starts_with("datetime")) SetType(Type::DateTime);
	else if (colType._Starts_with("double")) SetType(Type::Double);
	else if (colType._Starts_with("float")) SetType(Type::Float);
	else if (colType._Starts_with("int")) SetType(Type::Int);
	else if (colType._Starts_with("json")) SetType(Type::Json);
	else if (colType._Starts_with("longblob")) SetType(Type::LongBlob);
	else if (colType._Starts_with("longtext")) SetType(Type::LongText);
	else if (colType._Starts_with("mediumblob")) SetType(Type::MediumBlob);
	else if (colType._Starts_with("mediumint")) SetType(Type::MediumInt);
	else if (colType._Starts_with("mediumtext")) SetType(Type::MediumText);
	else if (colType._Starts_with("varchar")) {
		SetType(Type::VarChar);
		m_DataLen = extract1(colType);
	}
	else if (colType._Starts_with("text")) SetType(Type::Text);
	else if (colType._Starts_with("time")) SetType(Type::Time);
	else if (colType._Starts_with("timestamp")) SetType(Type::Timestamp);
	else if (colType._Starts_with("tinyblob")) SetType(Type::TinyBlob);
	else if (colType._Starts_with("tinyint")) SetType(Type::TinyInt);
	else if (colType._Starts_with("tinytext")) SetType(Type::TinyText);
	else if (colType._Starts_with("smallint")) SetType(Type::SmallInt);
	else if (colType._Starts_with("varbinary")) {
		SetType(Type::VarBinary);
		m_DataLen = extract1(colType);
	}
	else if (colType._Starts_with("year")) SetType(Type::Year);
	else {
		SetType(Type::Unknown);
	}
}